package com.hrm.common.interceptor;

import com.hrm.common.entity.ResultCode;
import com.hrm.common.exception.CommonException;
import com.hrm.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 林海湾Sea
 * @Date :  2021/12/10 17:10
 * @Decription:
 *
 * 自定义拦截器：
 *      继承HandlerInterceptorAdapter
 *
 *      1、preHandle:进入到控制器方法之前执行的内容
 *          boolean:
 *              true: 可以继续执行控制器方法
 *              false：拦截
 *      2、posthandler: 执行控制器方法之后执行的内容
 *      3、afterCompletion: 响应结束之前执行的内容
 *
 *  1、简化获取token数据的代码编写
 *      统一的用户权限校验（是否登录）
 *  2、判断用户是否具有当前访问接口的权限
 *
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、通过request获取请求token信息
        String authorization = request.getHeader("Authorization");
        // 2、判断请求头信息是否为空，或者是否以Bearer开头
        if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer")) {
            // 获取token数据
            String token = authorization.replace("Bearer", "");
            // 解析token获取claims
            Claims claims = jwtUtils.parseJwt(token);
            if (null != claims) {
                // 通过claims获取到当前用户可以访问的API权限字符串
                String apis = (String) claims.get("apis");
                // 通过handler
                HandlerMethod h = (HandlerMethod) handler;
                // 获取接口上的requestmapping注解
                RequestMapping annotation = h.getMethodAnnotation(RequestMapping.class);
                // 获取当前请求接口中的name属性
                String name = annotation.name();
                // 判断当前用户是否具有相应的请求权限
                if (apis.contains(name)) {
                    request.setAttribute("user_claims", claims);
                    return true;
                } else {
                    // 抛出异常、权限不足
                    throw new CommonException(ResultCode.UNAUTHORISE);
                }
            }
        }
        throw new CommonException(ResultCode.UNAUTHENTICATED);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
